<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/10/10
 * Time: 16:09
 */
namespace App\Services\JMessage;

use JMessage\IM\Message;
use JMessage\IM\Resource;
use JMessage\IM\User;
use JMessage\JMessage;

class JMessageService
{
    private $appKey;
    private $masterSecret;

    public function __construct()
    {
        $this->appKey = config('im.jiguang_im.appKey');
        $this->masterSecret = config('im.jiguang_im.masterSecret');
    }

    /**
     * 获取im对象
     * @return JMessage
     */
    public function getClient()
    {
        // 禁用 SSL 证书的验证
        return new JMessage($this->appKey, $this->masterSecret, [ 'disable_ssl' => true ]);
    }

    /**
     * 获取签名
     * @return string
     */
    public function getSign()
    {
        $encodeParams = "appkey=" . $this->appKey . "&timestamp=" . time()
            . "&random_str=" . $this->createNonceStr() . "&key=" . $this->masterSecret;
        $signature = md5($encodeParams);
        return $signature;
    }

    /**
     * 随机字符串
     * @param int $length
     * @return string
     */
    public function createNonceStr($length = 36)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 获取用户对象
     * @param $client
     * @return User
     */
    public function user($client)
    {
        return new User($client);
    }

    /**
     * 注册用户
     * @param $username
     * @param $password
     * @return mixed
     */
    public function register($username, $password)
    {
        $user = $this->user($this->getClient());
        $response = $user->register($username, md5($password));
        return $response;
    }

    /**
     * 批量注册用户
     * @param array $users
     * @return mixed
     */
    public function batchRegister(array $users)
    {
//        $users = [
//            ['username' => 'username0', 'password' => 'password0'],
//            ['username' => 'username1', 'password' => 'password1'],
//            ['username' => 'jiguang', 'password' => 'password']
//        ];
        $user = $this->user($this->getClient());
        $response = $user->batchRegister($users);
        return $response;

    }

    /**
     * 获取用户列表
     * @param $count
     * @param int $start
     * @return mixed
     */
    public function listAll($count, $start = 0)
    {
        $user = $this->user($this->getClient());
        $response = $user->listAll($count, $start);
        return $response;
    }

    /**
     * 获取用户信息
     * @param $username
     * @return mixed
     */
    public function show($username)
    {
        $user = $this->user($this->getClient());
        $response = $user->show($username);
        return $response;
    }

    /**
     * 更新用户信息
     * @param $username
     * @param array $options
     * $options: 更新选项数组，表示需要更新的用户信息和值。支持 nickname、avatar、birthday、signature、gender、region、address 中的一个或多个
     * 参数	     意义	                说明
     * nickname	（选填）用户昵称	不支持的字符：英文字符： \n \r\n
     * avatar	（选填）头像	需要填上从文件上传接口获得的 media_id
     * birthday	（选填）生日	example: 1990-01-24 yyyy-MM-dd
     * signature	（选填）签名	支持的字符：全部，包括 Emoji
     * gender	（选填） 性别	0 - 未知， 1 - 男 ，2 - 女
     * region	（选填）地区	支持的字符：全部，包括 Emoji
     * address	（选填）地址	支持的字符：全部，包括 Emoji
     * @return mixed
     */
    public function update($username, array $options)
    {
        $user = $this->user($this->getClient());
        $response = $user->update($username, $options);
//        $response = $user->update($username, ['nickname' => $nickname， 'gender' => 2]);
        return $response;
    }

    /**
     * 获取用户在线状态
     * @param $username
     * @return mixed
     */
    public function status($username)
    {
        $user = $this->user($this->getClient());
        $response = $user->stat($username);
        return $response;
    }

    /**
     * 修改用户密码
     * @param $username
     * @param $password
     * @return mixed
     */
    public function updatePassword($username, $newPassword)
    {
        $user = $this->user($this->getClient());
        $response = $user->updatePassword($username, $newPassword);
        return $response;
    }

    /**
     * 删除用户
     * @param $username
     * @return mixed
     */
    public function delete($username)
    {
        $user = $this->user($this->getClient());
        $response = $user->delete($username);
        return $response;
    }

    /**
     * 禁用用户
     * @param $username
     * @param $enabled true 表示禁用用户，false 表示取消禁用用户，即激活用户
     * @return mixed
     */
    public function forbidden($username, $enabled)
    {
        $user = $this->user($this->getClient());
        $response = $user->forbidden($username, $enabled);
        return $response;
    }

    /**
     * 获取消息对象
     * @param $client
     */
    public function getMessage($client)
    {
        return new Message($client);
    }

    /**
     * 发送文本消息
     * @param $version
     * @param array $from
     * @param array $target
     * 发送目标类型 single - 个人，group - 群组 chatroom - 聊天室（必填）
     * @param array $msg
     * @param array $notification
     * @param array $options
     * @return mixed
     */
    public function sendText($version, array $from, array $target, array $msg, array $notification = [], array $options = [])
    {
        $message = $this->getMessage($this->getClient());
        $response = $message->sendText($version, $from, $target, $msg, $notification, $options);
        return $response;
    }

    public function sendImage($version, array $from, array $target, array $msg, array $notification = [], array $options = [])
    {
        $message = $this->getMessage($this->getClient());
        $response = $message->sendImage($version, $from, $target, $msg, $notification, $options);
        return $response;
    }

    public function getResource($client)
    {
        return new Resource($client);
    }

    /**
     * 上传资源文件
     * @param $type '表示要上传的资源类型，支持 'image' 、'voice' 和 'file' 三种资源类型'
     * @param $path '表示要上传的资源的全路径，可以是本地也可以是远程'
     * @return mixed
     */
    public function upload($type, $path)
    {
        $resource = $this->getResource($this->getClient());
        $response = $resource->upload($type, $path);
        return $response;
    }

    /**
     * 获取发送消息定制格式
     * @param $msgType '消息类型：0001个人，0002公告 0003活动'
     * @param $scene '业务场景：1还款计划，2还款收益，3收银，4收银收益，5会员升级，6会员升级收益，7办卡申请，8办卡收益，9出账，10公告，11活动'
     * @param $id
     * @param $title
     * @param $content
     * @param $url
     * @return array
     */
    public function getExtras($msgType, $scene, $id, $title, $content, $imageUrl, $webUrl)
    {
        return [
            'msg_type' => $msgType,
            'scene' => $scene,
            'detail_id' => $id,
            'title' => $title,
            'content' => $content,
            'image_url' => $imageUrl,
            'web_url' => $webUrl
        ];
    }

    /**
     * 发送文本消息-私聊
     * @param $toId 15044668 热门活动 15044666 官方公告
     * @param $sendType 'single', 'chatroom'
     * @param $text
     * @param $msgType
     * @param $scene
     * @param $id
     * @param $title
     * @param $content
     * @param $imageUrl
     * @param $url
     */
    public function sendTextMessage($toId, $sendType, $text, $msgType, $scene, $id, $title, $content, $imageUrl, $webUrl)
    {
        $from = [
            'id'   => '0000',
            'type' => 'admin'
        ];
        $target = [
            'id'   => $toId,
            'type' => $sendType
        ];
        $msg = [
            'text' => $text,
            'extras' => $this->getExtras($msgType, $scene, $id, $title, $content, $imageUrl, $webUrl)
        ];
        return $this->sendText(1, $from, $target, $msg);
    }

    /**
     * 发送图文消息-聊天室
     */
    public function sendImageToChatRoom($toId)
    {
        $image = $_SERVER['DOCUMENT_ROOT'] . '/web/user/images/banner.png';
        $response = $this->upload('image', $image);
        $from = [
            'id'   => '0000',
            'type' => 'admin'
        ];
        $target = [
            'id'   => $toId,
            'type' => 'chatroom'
        ];
        $msg = $response['body'];
        return $this->sendImage(1, $from, $target, $msg);
    }

}